package ilincar.systemcore.model;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;

import com.gilda.fmupdate.MainA;

import android.location.LocationManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.annotation.NonNull;

import ilincar.systemcore.tool.ILog;
import ilincar.systemcore.util.SpUtil;

import java.lang.reflect.Method;

/**
 * Created by ilincar on 2016/12/15.
 * 系统状态管理类
 */

public class SystemState {

    private final String TAG = "SystemState";

    private Context mContext = null;

    private WifiManager mWifiManager = null;
    private LocationManager mLocationManager = null;

    private BluetoothAdapter mBluetoothAdapter = null;


    private boolean isDSAWorking = false;
    /**
     * 打开雷达,DSA
     */
    private final String ACTION_OPEN_DSA = "dsa.action.speech.to.open.radar";

    /**
     * 关闭雷达,DSA
     */
    private final String ACTION_CLOSE_DSA = "dsa.action.speech.to.close.radar";

    /**
     * 退出雷达
     */
    private final String ACTION_EXIT_DSA = "com.action.aios.to.dsa.exit";

    /**
     * 关闭DSA声音
     */
    private final String ACTION_MUTE_DSA = "com.action.aios.to.dsa.mute";

    /**
     * 恢复DSA声音
     */
    private final String ACTION_UNMUTE_DSA = "com.action.aios.to.dsa.unmute";

    /**
     * 关闭DSA声音,但RESUME时恢复
     */
    private final String ACTION_MUTE_RESUME_DSA = "com.action.aios.to.dsa.mute.auto";

    //断开蓝牙电话连接广播
    public static final String ACTION_DISCONNECT_DEVICE_BT = "action_disconnect_device_bt";

    // 通知设置App更改蓝牙状态广播
    public static final String ACTION_BT_FM_STATUS = "action_bt_fm_status";

    private boolean a2dp = false;
    private Intent btIntent;

    /**
     * 熄火前各种状态缓存
     */
    // GPS是否打开
    private boolean mIsGpsOpen = false;
    // 蓝牙是否打开
    private boolean mIsBtOpen = false;
    // FM是否打开
    private boolean mIsFmOpen = false;
    // 蓝牙电话是否
    private boolean mIsBtPhoneLink = false;
    // Wifi是否打开
    private boolean mIsWifiOpen = false;
    // Wifi热点是否打开
    private boolean mIsWifiApOpen = false;
    // 雷达与dsa声音是否打开
    private boolean mIsDsaUnmute = false;
    /**是否已经熄火**/
    private boolean isFireOff = false;

    public SystemState(@NonNull Context context) {
        this.mContext = context;
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        init();
    }

    /**
     * 初始化状态
     */
    private void init() {
        /*closeWifi();
        setWifiAp(false);
        closeSystemBt();
        closeFm();*/
        Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, true);
    }

    /**
     * 车机打火
     */
    public void start() {
        isFireOff = false;
        readState();

        StringBuffer sb = new StringBuffer();
        //恢复WIFI状态
        if (mIsWifiOpen)
            openWifi();
        sb.append(" wifi:" + mIsWifiOpen);

        //恢复GPS状态
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) != mIsGpsOpen)
            Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, mIsGpsOpen);
        sb.append(" gps:" + mIsGpsOpen);

        // 恢复蓝牙状态
        if (mIsBtOpen)
            openSystemBt();
        sb.append(" bt:" + mIsBtOpen);

        // 恢复Wifi热点状态
        if (mIsWifiApOpen)
            setWifiAp(true);
        sb.append(" wifiAp:" + mIsWifiApOpen);

        // 恢复FM状态
        if (mIsFmOpen) {
            openFm();
        }
        sb.append(" fm:" + mIsWifiOpen);

        // 打开DSA声音
        openDsa();

        ILog.i("打火状态:" + sb.toString());

    }

    /**
     * 车机熄火
     */
    public void sleep() {

        if (isFireOff)
            return;
        isFireOff = true;

        StringBuffer sb = new StringBuffer();
        //关闭WIFI
        mIsWifiOpen = mWifiManager.isWifiEnabled();
        closeWifi();
        sb.append(" wifi:" + mIsWifiOpen);

        //如果WIFI热点打开了，则进行关闭
        mIsWifiApOpen = isWifiApEnabled();
        setWifiAp(false);
        sb.append(" wifiAp:" + mIsWifiApOpen);

        //如果GPS热点打开了，则进行关闭
        mIsGpsOpen = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (mIsGpsOpen) {
            Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, false);
        }
        sb.append(" gps:" + mIsGpsOpen);

        //如果蓝牙发射打开，则进行关闭
        if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
            mIsBtOpen = true;
        } else {
            mIsBtOpen = false;
        }
        sb.append(" bt:" + mIsBtOpen);
        closeSystemBt();

        //如果FM状态打开，则进行关闭
        mIsFmOpen = MainA.getInstance().getFMLauncherStatus();
        closeFm();
        sb.append(" fm:" + mIsFmOpen);

        // 关闭DSA声音
        closeDsa();

        // 关闭蓝牙电话连接
        sendBroadcast(ACTION_DISCONNECT_DEVICE_BT);

        ILog.i("熄火前状态:" + sb.toString());

        writeState();
    }

    /***
     * 读取系统状态
     */
    private void readState() {
        // mIsGpsOpen = false;
        mIsGpsOpen = true;//SpUtil.getBooleanSharedPerference(mContext, "mIsGpsOpen");
        mIsBtOpen = SpUtil.getBooleanSharedPerference(mContext, "mIsBtOpen");
        mIsFmOpen = SpUtil.getBooleanSharedPerference(mContext, "mIsFmOpen");
        mIsBtPhoneLink = SpUtil.getBooleanSharedPerference(mContext, "mIsBtPhoneLink");
        mIsWifiOpen = SpUtil.getBooleanSharedPerference(mContext, "mIsWifiOpen");
        mIsWifiApOpen = SpUtil.getBooleanSharedPerference(mContext, "mIsWifiApOpen");
        mIsDsaUnmute = SpUtil.getBooleanSharedPerference(mContext, "mIsDsaUnmute");
    }

    private void writeState() {
        SpUtil.setBooleanSharedPerference(mContext, "mIsGpsOpen", mIsGpsOpen);
        SpUtil.setBooleanSharedPerference(mContext, "mIsBtOpen", mIsBtOpen);
        SpUtil.setBooleanSharedPerference(mContext, "mIsFmOpen", mIsFmOpen);
        SpUtil.setBooleanSharedPerference(mContext, "mIsBtPhoneLink", mIsBtPhoneLink);
        SpUtil.setBooleanSharedPerference(mContext, "mIsWifiOpen", mIsWifiOpen);
        SpUtil.setBooleanSharedPerference(mContext, "mIsWifiApOpen", mIsWifiApOpen);
        SpUtil.setBooleanSharedPerference(mContext, "mIsDsaUnmute", mIsDsaUnmute);
    }

    /**
     * 判断WIFI热点是否打开
     *
     * @return
     */
    private boolean isWifiApEnabled() {
        try {
            Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(mWifiManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置WIFI热点
     */
    private void setWifiAp(boolean state) {
        // 如果wifi打开，则需先关闭
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        try {
            Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration configuration = (WifiConfiguration) method.invoke(mWifiManager);
            Method apmethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            apmethod.invoke(mWifiManager, configuration, state);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开Wifi
     */
    private void openWifi() {
        setWifiAp(false);
        mWifiManager.setWifiEnabled(true);
    }

    /**
     * 关闭Wifi
     */
    private void closeWifi() {
        mWifiManager.setWifiEnabled(false);
    }

    /**
     * 打开DSA
     */
    private void openDsa() {
        //sendBroadcast(ACTION_UNMUTE_DSA);
    }

    /**
     * 关闭DSA
     */
    private void closeDsa() {
        sendBroadcast(ACTION_MUTE_DSA);
    }

    /**
     * 打开Fm
     */
    private void openFm() {
        // 如果蓝牙状态开启，则需要关闭
        mBluetoothAdapter.disable();
        MainA.getInstance().setFMLauncherOpen();
        float fm_freq = SpUtil.getPublicFloatSharePerference(mContext, "com.ilincar.carsettings", "Settings_public", "key_fm_freq");
        MainA.getInstance().setProgressValue(fm_freq);
        sendBroadcast(ACTION_BT_FM_STATUS);
    }

    /**
     * 关闭Fm
     */
    private void closeFm() {
        MainA.getInstance().setFMLauncherClose();
        sendBroadcast(ACTION_BT_FM_STATUS);
    }

    /**
     * 打开系统蓝牙
     */
    private void openSystemBt() {
        MainA.getInstance().setFMLauncherClose();
        mBluetoothAdapter.enable();
    }

    /**
     * 关闭系统蓝牙
     */
    private void closeSystemBt() {
        mBluetoothAdapter.disable();
    }

    /**
     * 发送外部广播
     */
    private void sendBroadcast(String action) {
        Intent i = new Intent(action);
        mContext.sendBroadcast(i);
    }

}
